# -*- encoding:utf-8 -*-

import http.client
import hashlib
import json
import urllib
import random
import time
import requests
import logging
from tkjs import TKJS

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class TranslateTool:
    baidu_appid = '20201203000635800'
    baidu_secret_key = 'QSV6xd8Zy0J6P8Bpz4no'

    def __init__(self):
        self.tk_js = TKJS()

    def baidu_translate(self, content, from_lang='en', to_lang='zh'):
        http_client = None
        url = '/api/trans/vip/translate'
        q = content
        salt = random.randint(32768, 65536)
        sign = self.baidu_appid + q + str(salt) + self.baidu_secret_key
        sign = hashlib.md5(sign.encode()).hexdigest()
        url = url + '?appid=' + self.baidu_appid + '&q=' + urllib.parse.quote(
            q) + '&from=' + from_lang + '&to=' + to_lang + '&salt=' + str(
            salt) + '&sign=' + sign

        try:
            http_client = http.client.HTTPConnection('api.fanyi.baidu.com')
            http_client.request('GET', url)
            # response是HTTPResponse对象
            response = http_client.getresponse()
            json_response = response.read().decode("utf-8")  # 获得返回的结果，结果为json格式
            js = json.loads(json_response)  # 将json格式的结果转换字典结构
            dst = str(js["trans_result"][0]["dst"])  # 取得翻译后的文本结果
            time.sleep(1)  # 百度翻译api，普通版，QPS=1，所以只好等待1秒翻译一次
            if dst:
                return True, dst
            else:
                return False, dst
        except Exception as e:
            print(e)
            return 'translated error'
        finally:
            if http_client:
                http_client.close()

    # 有道翻译方法
    def youdao_translate(self, content):
        """
        实现有道翻译的接口
        :param content:
        :return:
        """

        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom=https://www.baidu.com/link'
        data = {'from': 'AUTO', 'to': 'AUTO', 'smartresult': 'dict', 'client': 'fanyideskweb', 'salt': '1500092479607',
                'sign': 'd9f9a3aa0a7b34241b3fe30505e5d436', 'doctype': 'json', 'version': '2.1', 'keyfrom': 'fanyi.web',
                'action': 'FY_BY_CL1CKBUTTON', 'typoResult': 'true', 'i': content}
        data = urllib.parse.urlencode(data).encode('utf-8')
        wy = urllib.request.urlopen(url, data)
        html = wy.read().decode('utf-8')
        ta = json.loads(html)
        ret = ta['translateResult'][0][0]['tgt']
        if ret:
            return True, ret
        else:
            return False, ret

    # 谷歌翻译方法
    def google_translate(self, content):
        """
        实现谷歌的翻译
        :param content:
        :return:
        """
        tk = self.tk_js.generateTk(content)

        if len(content) > 4891:
            print("翻译的长度超过限制！！！")
            return ''

        param = {'tk': tk, 'q': content}

        result = requests.get("""http://translate.google.cn/translate_a/single?client=t&sl=en 
            &tl=zh-CN&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss 
            &dt=t&ie=UTF-8&oe=UTF-8&clearbtn=1&otf=1&pc=1&srcrom=0&ssel=0&tsel=0&kc=2""", params=param, timeout=3)

        # 返回的结果为Json，解析为一个嵌套列表
        trans = result.json()[0]
        ret = ''
        for i in range(len(trans)):
            line = trans[i][0]
            if line is not None:
                ret += trans[i][0]
        if ret:
            return True, ret
        else:
            return False, ret

    def translate(self, content, funcs=[google_translate,
                                        baidu_translate,
                                        youdao_translate]):
        count = 0
        # 循环调用谷歌、百度、有道API，其中如果谁调成功就返回，或者大于等于9次没有成功也返回。
        while True:
            ret = (False, '')
            for i in range(len(funcs)):
                try:
                    ret = funcs[i](content)
                except Exception as e:
                    logger.info("调用 %s 方法出现异常。" % funcs[i].__name__)
                if ret[0]:
                    return ret[1]
                else:
                    count += 1
            if count == 9:
                logger.info("以下内容尝试9次仍翻译失败，内容【 %s 】" % content)
                return ''
            else:
                continue


if __name__ == '__main__':
    translate_tool = TranslateTool()
    boo, result = translate_tool.google_translate("translate")
    print(result)
